<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\hgapi\controller;
require_once('./static/api/api_sdk/vendor/autoload.php');
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use app\hgapi\model\system\Site;
use app\hgapi\model\system\Verify;
use app\hgapi\model\user\UserCarry;
use app\hgapi\model\user\UserChoose;
use app\hgapi\model\user\UserLead;
use app\hgapi\model\user\UserRole;
use app\hgapi\model\user\UserPackage;
use app\hgapi\model\user\User;
use app\hgapi\model\user\UserWriter;
use app\hgapi\model\user\UserScene;
use app\hgapi\model\activity\ActivityClockQian;
use app\hgapi\model\activity\ActivityClockRecord;
use app\hgapi\model\goods\GoodsGiftCode;
use app\hgapi\model\goods\GoodsGiftCodeRecord;
use app\hgapi\model\goods\GoodsGift;
use app\hgapi\model\goods\GoodsPackage;
use app\hgapi\model\store\StoreOrder;

// 加载区域结点配置
Config::load();
class TradeApi extends Auth{

    /**
     * 获取验证码
     */
    public function send_phone(){
        $phone = input('phone');
        if(empty($phone)){
            errorCode('请填写手机号');
        }else if(!preg_match("/^[1][3,4,5,7,8][0-9]{9}$/", $phone)){
            errorCode('请输入正确的手机号');
        }
        //验证是否注册过
        $is = User::getUserInfo(['phone' => $phone], '');
        if ($is){
            errorCode('该手机号已绑定,请更换手机号');
        }
        //验证时间有没有一分钟
        $codeInfo = Verify::getVerifyInfo(['phone' => $phone], 'id'); //查出手机号发送的验证码信息
        if ($codeInfo) $codeInfo = $codeInfo->toArray();
        if(!empty($codeInfo) && time() < $codeInfo['time'] + 60){
            errorCode('间隔不足60秒,请稍后重发');
        }else{
            $code = phoneCode();
            $content = "塔灯小程序新";
            $info = $this->sendSms($phone, '塔灯网络', 'SMS_27300215', $code, $content);
            $info = json_decode(json_encode($info), true);
            if($info['Code'] == 'OK'){
                $verify =  [
                    'phone' => $phone,
                    'code' => $code,
                    'time' => time()
                ];
                if($codeInfo){
                    $re = Verify::upVerify(['id' => $codeInfo['id']], $verify);
                    if($re){
                        successCode('验证码发送成功,请稍等短信通知');
                    }else{
                        errorCode('验证码发送失败,请重新获取');
                    }
                }else{
                    $re = Verify::add($verify);
                    if($re){
                        successCode('验证码发送成功,请稍等短信通知');
                    }else{
                        errorCode('验证码发送失败,请重新获取');
                    }
                }
            }else{
                errorCode('验证码发送异常,请联系管理员');
            }
        }
    }


    //新版阿里云短信
    static $acsClient = null;

    /**
     * 取得AcsClient
     *
     * @return DefaultAcsClient
     */
    public static function getAcsClient() {
        //产品名称:云通信流量服务API产品,开发者无需替换
        $product = "Dysmsapi";
        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";
        // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
        $accessKeyId = ''; // AccessKeyId
        $accessKeySecret = ''; // AccessKeySecret
        // 暂时不支持多Region
        $region = "cn-hangzhou";
        // 服务结点
        $endPointName = "cn-hangzhou";
        if(static::$acsClient == null) {
            //初始化acsClient,暂不支持region化
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
            // 增加服务结点
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
            // 初始化AcsClient用于发起请求
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }


    /**
     * 发送短信
     * @return stdClass
     */
    public static function sendSms($num,$sign,$tem_num,$code,$content) {
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();
        //可选-启用https协议
        //$request->setProtocol("https");
        // 必填，设置短信接收号码
        $request->setPhoneNumbers($num);
        // 必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $request->setSignName($sign);
        // 必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $request->setTemplateCode($tem_num);
        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
            "code" => $code,
            "product" => $content
        ), JSON_UNESCAPED_UNICODE));
        // 可选，设置流水号
        $request->setOutId("E0029393");
        // 选填，上行短信扩展码（扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段）
        $request->setSmsUpExtendCode("1234567");
        // 发起访问请求
        $acsResponse = static::getAcsClient()->getAcsResponse($request);
        return $acsResponse;
    }

    /**
     * 提供礼品商家申请
     */
    public function carry(){
        $id = input('id'); //用户id
        $phone = input('phone'); //手机号
        $recruit = input('recruit'); //业务员
        $name = input('name'); //店铺名称
        $latitude = input('latitude'); //礼品数量
        $longitude = input('longitude'); //礼品数量
        $address = input('address'); //商家地址
        $status = input('status'); //状态0待审核 3未支付押金
        $carry = UserCarry::getCarryInfo(['uid' => $id, 'status' => 0], '');
        if ($carry){
            errorCode('正在审核中,请耐心等待');
        }else{
            $data = [
                'uid' => $id,
                'phone' => $phone,
                'recruit' => $recruit,
                'status' => $status,
                'name' => $name,
                'latitude' => $latitude,
                'longitude' => $longitude,
                'address' => $address,
            ];
            $result = UserCarry::add($data);
            if ($result){
                successCode('提交成功,请等待审核');
            }else{
                errorCode('提交失败');
            }
        }
    }

    /**
     * 添加获客活动
     */
    public function addhuo(){
        $id = input('id'); //用户id
        $lipin = input('lipin'); //礼品名称
        $price = input('price'); //礼品价值
        $num = input('num'); //礼品每期数量
        $stage = input('stage'); //期数
        $img = input('img'); //期数
        $ge = input('ge'); //期数
        $mode = input('mode'); //领取方式
        $gold = input('gold'); //佣金
        $address = input('address'); //商家地址
        $latitude = input('latitude');
        $longitude = input('longitude');
        $beizhu = input('beizhu'); //备注
        $status = input('status');
        $zu = input('zu');
        if (!$lipin){
            errorCode('请输入礼品名称');
        }
        if (!$num){
            errorCode('请输入礼品数量');
        }elseif (!is_numeric($num)){
            errorCode('请输入正确的礼品数量');
        }
        if (!$stage) errorCode('请输入期数');
        if (!$ge) errorCode('请输入领取间隔天数');
        $data = [
            'uid' => $id,
            'lipin' => $lipin,
            'price' => $price,
            'num' => $num,
            'stage' => $stage,
            'img' => $img,
            'ge' => $ge,
            'mode' => $mode,
            'gold' => $gold,
            'address' => $address,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'beizhu' => $beizhu,
            'status' => $status,
            'is_zu' => $zu,
        ];
        $id = GoodsGift::add($data);
        if ($id){
            successCode($id);
        }else{
            errorCode('提交失败');
        }
    }

    /**
     * 获取大礼包
     */
    public function package(){
        //查询所有大礼包
        $uid = input('uid');
        $package = GoodsPackage::selPackage(['end' => ['gt', time()], 'status' => 1]);
        foreach ($package as $k => $v){
            $gid = explode(',', $v['gid']);
            $package[$k]['libao'] = GoodsGift::selGift(['id' => ['in', $gid]]);
            $package[$k]['youxiao'] = ' 有效期: ' . date('Y-m-d', $v['start']) . ' - ' . date('Y-m-d', $v['end']);
        }
        $is = Site::getField('is_fei');
        $role = UserRole::getRole($uid);
        successCode(['package' => $package, 'is' => $is, 'role' => $role]);
    }

    /**
     * 引流商家申请
     */
    public function lead_continue(){
        $uid = input('uid'); //用户id
        $phone = input('phone'); //手机号
        $recruit = input('recruit'); //业务员
        $name = input('name'); //店铺名称
        $latitude = input('latitude'); //礼品数量
        $longitude = input('longitude'); //礼品数量
        $address = input('address'); //商家地址
        $lead = UserLead::getLead(['uid' => $uid, 'status' => 0], '');
        if ($lead) errorCode('正在审核中,请耐心等待');
        $data = [
            'uid' => $uid,
            'phone' => $phone,
            'recruit' => $recruit,
            'status' => 0,
            'name' => $name,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'address' => $address,
        ];
        $re = UserLead::add($data);
        if ($re){
            successCode('申请成功');
        }else{
            errorCode('申请失败请稍后重试');
        }
    }

    /**
     * 获取成为商家信息
     */
    public function become(){
        $type = input('type'); //0获取获客商家 1获取引流商家
        $content = Site::getField($type == 0 ? 'huo' : 'yin');
        successCode($content);
    }

    /**
     * 查看礼品领取情
     */
    public function ling(){
        $id = input('id'); //礼品id
        $list = GoodsGiftCode::selCode(['lid' => $id], ['status' => 1]);
        foreach ($list['data'] as $k => $v){
            $list['data'][$k]['time'] = $v['time'] ? date('Y-m-d', $v['time']) : '-';
            if ($v['uid']){

                $list['data'][$k]['uid'] = base64_decode(User::getField(['id' => $v['uid']], 'name', 0));
            }else{
                $list['data'][$k]['uid'] = '-';
            }
            if ($v['yid']){
                $list['data'][$k]['yid'] = base64_decode(User::getField(['id' => $v['yid']], 'name', 0));
            }else{
                $list['data'][$k]['yid'] = '-';
            }
        }
        successCode($list);
    }

    /**
     * 申请大礼包
     */
    public function choose_add(){
        $id = input('id'); //大礼包id
        $uid = input('uid'); //用户id
        $money = input('money'); //提交过来的礼包需支付价格
        $name = input('name'); //商家店铺名称
        $phone = input('phone'); //商家手机号
        //查询设置是否允许引流商家自己设置价格
        $status = UserChoose::getField(['uid' => $uid, 'package' => $id], 'status');
        if ($status === 0){
            errorCode('请等待审核通过');
        }elseif ($status === 1){
            errorCode('你已经申请此大礼包了');
        }
        $is = Site::getField('is_fei');
        if ($is == 0){
            $money = GoodsPackage::getField(['id' => $id], 'money');
        }
        //添加引流商家大礼包记录
        $data = [
            'uid' => $uid,
            'package' => $id,
            'status' => 0,
            'money' => $money,
        ];
        $re = UserChoose::add($data);
        $data2 = [
            'uid' => $uid,
            'recruit' => 0,
            'phone' => $phone,
            'status' => 0,
            'name' => $name,
        ];
        $re2 = UserLead::add($data2);
        if ($re && $re2){
            successCode('申请成功, 请等待审核');
        }else{
            errorCode('申请失败');
        }
    }

    /**
     * 查看引流商家大礼包
     */
    public function yin_package(){
        $id = input('id'); //用户id
        //package
        $list = UserChoose::selChooseZhi($id);
        foreach ($list as $k => $v){
            $list[$k]['time'] = date('Y-m-d', $v['start']) . ' - ' . date('Y-m-d', $v['end']);
        }
        successCode($list);
    }

    /**
     * 查看大礼包下面的礼品
     */
    public function cha_lipin(){
        $id = input('id'); //大礼包id
        $uid = input('uid'); //用户id
        //查询我的所有大礼包
        $package = UserPackage::getField(['uid' => $uid], 'package');
        $package = explode(',', $package);
        if (in_array($id, $package)){
            $is = 1;
        }else{
            $is = 0;
        }
        //查询大礼包下面的礼品
        $gid = GoodsPackage::getField(['id' => $id], 'gid');
        $gids = explode(',', $gid);
        $list = GoodsGift::selGift(['id' => ['in', $gids]]);
        foreach ($list as $k => $v){
            $list[$k]['index'] = numToWord($k+1);
        }
        successCode(['list' => $list, 'info' => $is]);
    }

    /**
     * 我提供的礼品
     */
    public function ti(){
        $id = input('id'); //用户id
        $list = GoodsGift::selGift(['uid' => $id]);
        foreach ($list as $k => $v){
            $list[$k]['jilu'] = GoodsGiftCodeRecord::countCodeRecord(['lid' => $v['id']]);
        }
        successCode($list);
    }

    /**
     * 我提供的大礼包z
     */
    public static function ti_package(){
        $id = input('id');
        $package = GoodsPackage::selPackage(['zid' => $id]);
        foreach ($package as $k => $v){
            $package[$k]['time'] = date('Y-m-d', $v['start']) . ' - ' . date('Y-m-d', $v['end']);
        }
        successCode($package);
    }

    /**
     * 引流商家短信
     */
    public function lead(){
        $phone = input('phone'); //手机号
        $vif = input('vif'); //验证码
        $recruit = input('recruit'); //业务员
        $find = Verify::getVerifyInfo(['phone' => $phone, 'code' => $vif], '');
        if ($find){
            //判断验证码是否过期 (5分钟)
            if ($find['time'] + 300 < time()){
                errorCode('验证码已过期,请重新发送');
            }else{
                successCode('成功');
            }
        }else{
            errorCode('请输入正确的验证码');
        }
    }

    /**
     * 获取添加下级核销员码
     */
    public function writer(){
        $id = input('id'); //用户id
        $writer = User::getField(['id' => $id], 'writer', 0);
        //查出下级核销员
        $list = UserWriter::selWriter(['uid' => $id]);
        foreach ($list as $k => $v){
            $list[$k]['name'] = base64_decode(User::getField(['id' => $v['xid']], 'name', 0));
            $list[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
        }
        if ($writer && file_exists($writer)){
            successCode(['img' => $writer, 'list' => $list]);
        }else{
            $access_token = access_token();
            $scene = "page:6,page_id:$id";
            $img = createImg($access_token, $scene);
            $name = $id.'-'.time();
            file_put_contents('uploads/writer/code-'.$name.'.png', $img);
            //存储二维码路径
            $img_url = 'uploads/writer/code-'.$name.'.png';
            User::upField(['id' => $id], 'writer', $img_url);
            successCode(['img' => $img_url, 'list' => $list]);
        }
    }

    /**
     * 增加下级核销员
     */
    public function writer_add(){
        $wid = input('wid'); //上级核销人
        $id = input('id'); //我的id
        $data = [
            'uid' => $wid,
            'xid' => $id,
            'time' => time(),
        ];
        $re = UserWriter::add($data);
        if ($re){
            successCode('添加成功');
        }else{
            successCode('添加失败');
        }
    }

    /**
     * 删除下级核销员
     */
    public function writer_del(){
        $id = input('id'); //要删除的核销人数据id
        $uid = input('uid'); //删除人
        $re = UserWriter::delWriter(['id' => $id, 'uid' => $uid]);
        if ($re){
            successCode('删除成功');
        }else{
            successCode('删除失败');
        }
    }

    /**
     * 核销
     */
    public function hexiao(){
        $id = input('id'); //当前扫码用户
        $page_id = input('page_id'); //相关数据
        $find = UserScene::getXcxSceneInfo(['id' => $page_id], '');
        $uid = $find['uid']; //核销的用户
        $lid = $find['lid']; //核销的礼品id
        $stage = $find['stage']; //核销的礼品期数
        $yid = $find['yid']; //当前引流商家
        //查出礼品所属人
        $gift = GoodsGift::getGift(['id' => $lid]);
        //查出是否为礼品人的下级核销员
        $uids = UserWriter::columnWriter(['xid' => $id], 'uid');
        if ($gift['uid'] == $id || in_array($gift['uid'], $uids)){
            //判断是否还有当前期数的核销码
            $cun = GoodsGiftCode::getCodeInfo(['lid' => $lid, 'stage' => $stage, 'status' => 0]);
            if (!$cun){
                errorCode('核销失败');
            }else{
                $data = [
                    'time' => time(),
                    'uid' => $uid,
                    'status' => 1,
                    'yid' => $yid,
                ];
                $re = GoodsGiftCode::upCode(['id' => $cun['id']], $data);
                if ($re){
                    //判断礼品是否有每单佣金
                    if ($gift['gold'] > 0){
                        $bi = Site::getSite('reward, reward2');
                        $ye = User::getField(['id' => $yid], 'recruit', 0);
                        //增加佣金
                        User::incField($yid, 'gold', round($bi['reward'] * $gift['gold'] / 100, 2));
                        User::incField($ye, 'gold', round($bi['reward2'] * $gift['gold'] / 100, 2));
                    }
                    $he = [
                        'uid' => $uid,
                        'h_time' => time(),
                        'lid' => $lid,
                        'stage' => $stage,
                        'hid' => $id,
                        'yid' => $yid,
                    ];
                    GoodsGiftCodeRecord::add($he);
                    successCode('核销成功');
                }else{
                    errorCode('核销失败');
                }
            }
        }else{
            errorCode('核销失败');
        }
    }

    /**
     * 绑定业务员
     */
    public function bin_business(){
        $id = input('id'); //用户id
        //查询出当前账户是否已经绑定
        $re = UserRole::upField(['uid' => $id], 'business', 1);
        if ($re){
            successCode('成功');
        }else{
            errorCode('失败');
        }
    }

    /**
     * 核销
     */
    public function hexiao2(){
        $id = input('id'); //扫码用户
        $uid = input('uid'); //核销的用户
        $oid = input('oid'); //订单id
        $yid = input('yid'); //所属商家
        //查出是否为商家的下级核销员
        $uids = UserWriter::columnWriter(['xid' => $id], 'uid');
        if ($yid == $id || in_array($yid, $uids)){
            //查询订单金额
            $order = StoreOrder::getOrderClockZhi($oid);
            if ($order['is_hx'] == 1){
                errorCode('已核销过');
            }
            $count = ActivityClockQian::countQian(['ch_id' => $ofid]);
            //判断签到是否成功
            if ($order['tian'] == $count && $count > 0){
                //增加余额
                User::incField($uid, 'cashback', $order['price']);
            }else{
                User::incField($yid, 'cashback', $order['price']);
            }
            $he = [
                'uid' => $uid,
                'oid' => $oid,
                'time' => time(),
                'hid' => $id,
                'yid' => $yid,
            ];
            ActivityClockRecord::add($he);
            StoreOrder::upField(['id' => $oid], 'is_hx', 1);
            successCode('核销成功');
        }else{
            errorCode('核销失败');
        }
    }
}